// components/goods-buy/index.js
import {
    apiUrl
} from '@/config/index'
import {
    pay
} from '@/services/pay/pay'
Component({

    /**
     * 组件的属性列表
     */
    properties: {
        goodInfo: {
            type: Object,
            value: {},
            observer(info) {
                this.setData({
                    productInfo: info
                })
            }
        },
        isShow: {
            type: Boolean,
            value: false,
            observer(isShow) {
                if (isShow) {
                    this.showPurchasePopup()
                } else {
                    this.hidePurchasePopup()
                }
            }
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        apiUrl,
        showPopup: false,
        quantity: 1,
        isPaying: false,
        productInfo: {},
        totalPrice: 0,
        selectedCoupon: null,
        showCouponPopup: false,
    },
    methods: {
        showPurchasePopup() {
            this.setData({
                showPopup: true,
                quantity: 1,
                totalPrice: this.computedTotalPrice()
            });
        },

        // 隐藏购买弹窗
        hidePurchasePopup() {
            this.setData({
                showPopup: false
            })
            this.triggerEvent('close', false)
        },

        // 处理数量变化
        handleQuantityChange(e) {
            this.setData({
                quantity: e.detail.value,
                totalPrice: this.computedTotalPrice(e.detail.value)
            });
        },

        showCouponPopup() {
            this.setData({
                showCouponPopup: true
            });
        },

        hideCouponPopup() {
            this.setData({
                showCouponPopup: false
            });
        },

        // 选择优惠券
        handleCouponChange(coupon) {
            this.setData({
                selectedCoupon: coupon,
                showCouponPopup: false,
            });
            setTimeout(() => {
                this.setData({
                    totalPrice: this.computedTotalPrice()
                })
            }, 100)
        },

        // 计算总价
        computedTotalPrice(value) {
            const {
                productInfo,
                quantity,
                selectedCoupon
            } = this.data;
            let total = productInfo.coursePrice * (value || quantity);
            if (selectedCoupon) {
                total -= 50;
                total = Math.max(total, 0); // 确保价格不小于0
            }
            return total.toFixed(2);
        },

        // 处理支付
        handlePayment() {
            if (this.data.isPaying) return;
            this.setData({
                isPaying: true
            });
            const userInfo = JSON.parse(wx.getStorageSync('userInfo') || '{}')
            // 准备支付参数
            if (userInfo && userInfo.customerId) {
                const {
                    productInfo,
                    quantity,
                    selectedCoupon,
                    totalPrice
                } = this.data;
                const paymentData = {
                    customerId: userInfo.customerId,
                    discountAmount: selectedCoupon ? 50 : 0,
                    buyNumber: quantity,
                    orderAmount: productInfo.coursePrice * quantity,
                    payAmount: totalPrice,
                    orderType: '00',
                    payMethod: '00',
                    relatedCoupon: selectedCoupon ? selectedCoupon.couponId : '',
                    relatedCourses: productInfo.courseCode
                };
                pay({
                    paymentData,
                    userInfo
                }, (data) => {
                    wx.redirectTo({
                        url: `/pages/order/pay-result/index?orderId=${data?.orderId}&orderType=${data?.orderType}&amount=${data?.payAmount}`
                    })
                }, () => {
                    this.setData({
                        isPaying: false
                    });
                })
            } else {
                this.setData({
                    isPaying: false
                });
                wx.navigateTo({
                    url: '/pages/login/login'
                })
            }
        }
    }
});